package com.ncu.web.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @Author:大润发杀鱼匠
 * @Date:2024/5/26 15:33 web
 */

@Component
public class JWTUtil {

    @Value(value = "${com.ncu.secret}")
    public  String secretKey;


    @PostConstruct
    public void init() {

    }

    /**
     * 生成token
     * @param username 用户名
     * @return token
     */
    public String createToken(String username) {
        Date now = new Date();
        //过期时间为3小时
        long expirationTime = 3600000 * 3;
        Date expiration = new Date(now.getTime() + expirationTime);

        return Jwts.builder()
                .claim("username", username)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256, secretKey.getBytes())
                .compact();
    }


    /**
     * 解析token获取用户名
     * @param token
     * @return 用户名
     */

    /** 获取用户名的方法
     *
     * Jws<Claims> claimsJws = parseToken(token);
     * String username = claimsJws.getBody().get("username", String.class);
     */
    public Jws<Claims> parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(secretKey.getBytes())
                .build()
                .parseClaimsJws(token);
    }

    /**
     * 判断登录是否过期
     * @param token
     * @return 布尔变量，true即没过期，false即过期
     */
    public boolean validateToken(String token) {
        try {
            Jws<Claims> claimsJws = parseToken(token);
            return !claimsJws.getBody().getExpiration().before(new Date());
        } catch (Exception e) {
            return false;
        }
    }
}